import axios from 'axios'
import config from '@/config/index'
import { Toast } from 'vant';
export default class Api {

    constructor(isBase = null) {
        this.instance = axios.create({
            baseURL: isBase == null ? config.checkEnvironment() : "",
            timeout: 10000,
            //headers: { 'X-Custom-Header': foobar }
        })
        this.interceptors()
    }
    async get(params) {
        return await this.instance.get(params.url, {
            params: params.data
        })
    }

    async post(params) {
        return await this.instance.post(params.url, params.data,{
            headers: Object.assign({ 
                "Content-Type": "application/json",
            }, params.headers)  //Object.assign  有值后面替换前面的
        })
    }
    //拦截器
    interceptors() {
        //请求前
        this.instance.interceptors.request.use(function (config) {
            Toast.loading({
                duration:10000,
                forbidClick: true,
                message: '加载中....',
            });
            return config
        }, function (error) {
            return Promise.reject(error);
        });
        //请求后返回的数据
        this.instance.interceptors.response.use(function (response) {
            
            Toast.clear();

            switch (response.data.status) {
                case 200:
                    return response.data.result
                    break;

                case 404:
                    Toast.fail({
                        message: response.data.message
                    });
                    throw new Error(response.data.message)
                    break;

                default:
                    break;
            }
        }, function (error) {
            return Promise.reject(error);
        });
    }
}